﻿using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Code;
using SmallShop.Services.Implements;
using SmallShop.Services.Interfaces;
using System;
using System.Web.Mvc;

namespace FrontEnd.Controllers
{
    public class MessageController : Controller
    {
        private readonly ICategoryService _CategoryService;
        private readonly IProvideService _ProvideService;
        private readonly IRequestService _RequestService;
        private readonly IUserService _UserService;
        private readonly ISkillService _SkillService;
        private readonly IBannerService _BannerService;
        private readonly IMMessageService _MMessageService;
        private readonly IMessageService _MessageService;
        private readonly IEmailFormatService _EmailFormatService;
        private readonly IMConversationService _MConversationService;

        public MessageController(ICategoryService CategoryService, IRequestService RequestService, IProvideService ProvideService, IUserService UserService, ISkillService SkillService, IBannerService BannerService, IMMessageService MMessageService, IMessageService MessageService, IEmailFormatService EmailFormatService, IMConversationService MConversationService)
        {
            _CategoryService = CategoryService;
            _RequestService = RequestService;
            _ProvideService = ProvideService;
            _UserService = UserService;
            _SkillService = SkillService;
            _BannerService = BannerService;
            _MMessageService = MMessageService;
            _MessageService = MessageService;
            _EmailFormatService = EmailFormatService;
            _MConversationService = MConversationService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SendMessage(int provideID, int reviceID, string contentMessage)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(false);
            }
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            var shortid = MessageHelper.BuildShortIDProvide(provideID, user.ID);
            var provide = _ProvideService.GetById(provideID);
            var receiver = _UserService.GetById(reviceID);
            MMessage m = new MMessage()
            {
                Content = contentMessage,
                Date = DateTime.Now,
                IsRead = false,
                ParentID = shortid,
                ReceiverID = reviceID,
                SenderID = user.ID,
                Type = (int)MessageType.PROVIDE
            };
            _MMessageService.Add(m);
            var cvs = _MConversationService.GetConversationByShortID(shortid);

            var unread = _MMessageService.CountUnread(reviceID);
            MessageHelper.SendMessageNotifyMessage(_MMessageService, Resources.Resource.SystemNotifyQuestion, unread, Resources.Resource.NumberMessageToNotify, reviceID, (cvs == null));

            if (cvs == null)
            {
                cvs = new MConversation()
                {
                    Message = m,
                    Person1ID = user.ID,
                    Person2ID = reviceID,
                    Provide = MongoConvert.ConvertProvide(provide),
                    ShortID = shortid,
                    Type = (int)MessageType.PROVIDE,
                    User1 = MongoConvert.ConvertUser(user),
                    User2 = MongoConvert.ConvertUser(receiver)
                };
                _MConversationService.Add(cvs);
            }

            //send notify
            //try catch to enable and disable send email depend on resource
            try
            {
                var format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailMessage));
                var email = UserUtility.GetVerifiedEmail(receiver);
                DictionaryMessage dicmes = new DictionaryMessage(email, user.ProperName, provide.Title, shortid);
                UserUtility.NotifyEmail(format, dicmes);
            }
            catch (Exception) { }
            return Json(true);
        }

        public ActionResult SendMessageRequest(int requestID, int reviceID, string contentMessage)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(false);
            }
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            var shortid = MessageHelper.BuildShortIDRequest(requestID, user.ID);
            var receiver = _UserService.GetById(reviceID);
            var request = _RequestService.GetById(requestID);
            MMessage m = new MMessage()
            {
                Content = contentMessage,
                Date = DateTime.Now,
                IsRead = false,
                ParentID = shortid,
                ReceiverID = reviceID,
                SenderID = user.ID,
                Type = (int)MessageType.REQUEST
            };
            _MMessageService.Add(m);
            var cvs = _MConversationService.GetConversationByShortID(shortid);

            var unread = _MMessageService.CountUnread(reviceID);
            MessageHelper.SendMessageNotifyMessage(_MMessageService, Resources.Resource.SystemNotifyQuestion, unread, Resources.Resource.NumberMessageToNotify, reviceID, (cvs == null));

            if (cvs == null)
            {
                cvs = new MConversation()
                {
                    Message = m,
                    Person1ID = user.ID,
                    Person2ID = reviceID,
                    Request = MongoConvert.ConvertRequest(request),
                    ShortID = shortid,
                    Type = (int)MessageType.REQUEST,
                    User1 = MongoConvert.ConvertUser(user),
                    User2 = MongoConvert.ConvertUser(receiver)
                };
                _MConversationService.Add(cvs);
            }
            //send notify
            //try catch to enable and disable send email depend on resource
            EmailFormat format = null;
            DictionaryMessage dicmes = null;
            try
            {
                format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailMessage));
                var email = UserUtility.GetVerifiedEmail(receiver);
                dicmes = new DictionaryMessage(email, user.ProperName, request.Title, shortid);
                UserUtility.NotifyEmail(format, dicmes);


            }
            catch (Exception) { }
            if (!string.IsNullOrWhiteSpace(request.ForwardEmail))
            {
                try
                {
                    format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailForwardMessage));
                    dicmes = new DictionaryForwardMessage(request.ForwardEmail, user.ProperName, request.Title, shortid, m.Content);
                    UserUtility.NotifyEmail(format, dicmes);
                }
                catch (Exception) { }
            }
            return Json(true);
        }

        public ActionResult GetUnread()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(0);
            }
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            return Json(_MMessageService.CountUnread(user.ID));
        }

        public ActionResult GetUnreadOrder()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(0);
            }
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            return Json(_MMessageService.CountUnreadOrder(user.ID));
        }

        public ActionResult ShowNotify()
        {
            Response.StatusCode = 404;
            return RedirectToAction("Error404", "Error");
            //if (!User.Identity.IsAuthenticated)
            //{
            //    Response.StatusCode = 404;
            //    return RedirectToAction("Error404", "Error");
            //}
            //var user = UtilityService.GetLoginUser(_UserService, User);
            //var lst = _MMessageService.GetNewwestNotity(user.ID);
            //foreach (var item in lst)
            //{
            //    item.Parent = _MConversationService.GetConversationByShortID(MessageHelper.GetShortIDRealParentNotify(item.ParentID));
            //}
            //ViewData["lst"] = lst;
            //return View();
        }

        public ActionResult ShowNotifyPV(int page)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error404", "Error");
            }
            if (page == 0)
            {
                return Json(false);
            }
            var user = UtilityService.GetLoginUser(_UserService, User);
            long total = 0;
            int pagesize = Convert.ToInt32(Resources.Resource.DisplayNotifyPerPage);
            var lst = _MMessageService.GetNotifyByPage(page, pagesize, out total, user.ID);
            foreach (var item in lst)
            {
                item.Parent = _MConversationService.GetConversationByShortID(MessageHelper.GetShortIDRealParentNotify(item.ParentID));
            }
            ViewData["lst"] = lst;
            if (page * pagesize < total)
            {
                ViewData["nextpage"] = page + 1;
            }
            return PartialView();
        }
        public ActionResult GetCountNotify()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(0);
            }
            var user = UtilityService.GetLoginUser(_UserService, User);
            var count = _MMessageService.CountNewwestNotity(user.ID);
            return Json(count);
        }
        public ActionResult RedirectNotify(string to,string notifyid)
        {
            if (String.IsNullOrWhiteSpace(to))
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error404", "Error");
            }
            var url = MessageHelper.GetShortIDRealParentNotify(to);
            if (String.IsNullOrWhiteSpace(url))
            {
                return Redirect("/hom-thu-ca-nhan");
            }
            else if (MessageHelper.CheckIsShortIDOrder(url))
            {
                var orderid = MessageHelper.GetOrderID(url);
                var intorderid = 0;
                if (!Int32.TryParse(orderid, out intorderid))
                {
                    Response.StatusCode = 404;
                    return RedirectToAction("Error404", "Error");
                }
                else
                {
                    return RedirectToAction("Details", "Order", new { id = intorderid });
                }
            }
            else if (MessageHelper.CheckIsShortIDRequest(url))
            {
                  var rqid = MessageHelper.GetRequestID(url);
                var intrqid = 0;
                if (!Int32.TryParse(rqid, out intrqid))
                {
                    Response.StatusCode = 404;
                    return RedirectToAction("Error404", "Error");
                }
                else
                {
                    return RedirectToAction("Details", "Request", new { id = intrqid });
                }
            }
            else if (MessageHelper.CheckIsShortIDProvide(url))
            {
                var rqid = MessageHelper.GetProvideID(url);
                var intrqid = 0;
                if (!Int32.TryParse(rqid, out intrqid))
                {
                    Response.StatusCode = 404;
                    return RedirectToAction("Error404", "Error");
                }
                else
                {
                    return RedirectToAction("Details", "Provide", new { id = intrqid });
                }
            }
            else
            {
                Response.StatusCode = 404;
                return RedirectToAction("Error404", "Error");
            }
        }
        public ActionResult SetReadNotify(string notifyid)
        {
            if (string.IsNullOrWhiteSpace(notifyid))
            {
                return Json(false);
            }
            _MMessageService.SetReadNotify(notifyid);
            return Json(true);
        }

        public ActionResult CallaModalComplaint(int orderid)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);

            var user = UtilityService.GetLoginUser(_UserService, User);
            if (string.IsNullOrWhiteSpace(user.Phone)) ViewData["needphone"] = true;
            ViewData["user"] = user;
            ViewData["orderid"] = orderid;
            return PartialView();
        }
        [HttpPost]
        public ActionResult SendComplaint(string complaint, string phone, int orderid)
        {
            if (!User.Identity.IsAuthenticated) return Json(false);
            var user = UtilityService.GetLoginUser(_UserService, User);
            if (!string.IsNullOrWhiteSpace(phone))
            {
                user.Phone = phone;
                _UserService.Update(user);
            }
            var info = new MMessageEmbedInfo()
            {
                Phone = user.Phone
            };
            MessageHelper.SendMessageComplaint(_MMessageService, complaint, MessageHelper.BuildShortIDComplaint(MessageHelper.BuildShortIDOrder(orderid)), user.ID, info);
            return Json(true);
        }
    }
}